import { Router } from 'express';
import { db } from '../utils/db.js';
import { requireRole } from '../utils/auth.js';

const router = Router();

router.get('/users', requireRole('ADMIN'), (req, res) => {
  const users = db
    .prepare('SELECT id, username, role, company_name, legal_person, phone, created_at FROM users ORDER BY created_at DESC')
    .all();
  if (req.accepts('html')) {
    return res.render('admin_users', { users, title: '用户管理' });
  }
  return res.json(users);
});

router.post('/users/:id/role', requireRole('ADMIN'), (req, res) => {
  const { role } = req.body;
  if (!['BIDDER', 'TENDERER', 'ADMIN'].includes(role)) {
    return res.status(400).render('error', { message: '非法角色类型' });
  }
  db.prepare('UPDATE users SET role=? WHERE id=?').run(role, req.params.id);
  res.redirect('/admin/users');
});

router.post('/messages/:id/delete', requireRole('ADMIN'), (req, res) => {
  db.prepare('DELETE FROM messages WHERE id = ?').run(req.params.id);
  res.redirect('/messages');
});

export default router;


